package org.jeecg.modules.basic.demo.school.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.IdGeneratorSnowflake;
import org.jeecg.common.util.YouBianCodeUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.apartment.entity.LwgyBaseApartment;
import org.jeecg.modules.basic.demo.apartment.service.ILwgyBaseApartmentService;
import org.jeecg.modules.basic.demo.bed.controller.LwgyBaseBedController;
import org.jeecg.modules.basic.demo.school.entity.ImportSchool;
import org.jeecg.modules.basic.demo.school.entity.LwgyBaseSchool;
import org.jeecg.modules.basic.demo.school.entity.SchoolTreeModel;
import org.jeecg.modules.basic.demo.school.mapper.LwgyBaseSchoolMapper;
import org.jeecg.modules.basic.demo.school.service.ILwgyBaseSchoolService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: lwgy_base_school
 * @Author: jeecg-boot
 * @Date: 2021-01-24
 * @Version: V1.0
 */
@Api(tags = "lwgy_base_school")
@RestController
@RequestMapping("/school/lwgyBaseSchool")
@Slf4j
public class LwgyBaseSchoolController extends JeecgController<LwgyBaseSchool, ILwgyBaseSchoolService> {
    @Autowired
    private ILwgyBaseSchoolService lwgyBaseSchoolService;
    @Autowired
    private LwgyBaseSchoolMapper lwgyBaseSchoolMapper;

    @Autowired
    private ILwgyBaseApartmentService lwgyBaseApartmentService;
    @Autowired
    private IdGeneratorSnowflake snowflake;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private CommonAPI commonAPI;

    @Autowired
    private LwgyBaseBedController lwgyBaseBedController;

    /**
     * 分页列表查询
     *
     * @param lwgyBaseSchool
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "lwgy_base_school-分页列表查询")
    @ApiOperation(value = "lwgy_base_school-分页列表查询", notes = "lwgy_base_school-分页列表查询")
    @GetMapping(value = "/rootList")
    public Result<?> queryPageList(LwgyBaseSchool lwgyBaseSchool,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        SpringBeanJobFactory springBeanJobFactory = new SpringBeanJobFactory();
        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            QueryWrapper<LwgyBaseSchool> queryWrapper = QueryGenerator.initQueryWrapper(lwgyBaseSchool, req.getParameterMap());
            List<LwgyBaseSchool> list = lwgyBaseSchoolService.queryTreeListNoPage(queryWrapper);
            IPage<LwgyBaseSchool> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } else {
            String parentId = lwgyBaseSchool.getPid();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            lwgyBaseSchool.setPid(null);
            QueryWrapper<LwgyBaseSchool> queryWrapper = QueryGenerator.initQueryWrapper(lwgyBaseSchool, req.getParameterMap());
            // 使用 eq 防止模糊查询
            queryWrapper.eq("pid", parentId);
            Page<LwgyBaseSchool> page = new Page<LwgyBaseSchool>(pageNo, pageSize);
            IPage<LwgyBaseSchool> pageList = lwgyBaseSchoolService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
    }

    /**
     * 获取子数据
     *
     * @param lwgyBaseSchool
     * @param req
     * @return
     */
    @AutoLog(value = "lwgy_base_school-获取子数据")
    @ApiOperation(value = "lwgy_base_school-获取子数据", notes = "lwgy_base_school-获取子数据")
    @GetMapping(value = "/childList")
    public Result<?> queryPageList(LwgyBaseSchool lwgyBaseSchool, HttpServletRequest req) {
        QueryWrapper<LwgyBaseSchool> queryWrapper = QueryGenerator.initQueryWrapper(lwgyBaseSchool, req.getParameterMap());
        List<LwgyBaseSchool> list = lwgyBaseSchoolService.list(queryWrapper);
        IPage<LwgyBaseSchool> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
        return Result.OK(pageList);
    }

    /**
     * 批量查询子节点
     *
     * @param parentIds 父ID（多个采用半角逗号分割）
     * @param parentIds
     * @return
     */
    @AutoLog(value = "lwgy_base_school-批量获取子数据")
    @ApiOperation(value = "lwgy_base_school-批量获取子数据", notes = "lwgy_base_school-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<LwgyBaseSchool> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<LwgyBaseSchool> list = lwgyBaseSchoolService.list(queryWrapper);
            IPage<LwgyBaseSchool> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }

    /**
     * 添加--一会修改
     *
     * @param lwgyBaseSchool
     * @return
     */
/*
    @AutoLog(value = "lwgy_base_school-添加")
    @ApiOperation(value = "lwgy_base_school-添加", notes = "lwgy_base_school-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody LwgyBaseSchool lwgyBaseSchool) {
        lwgyBaseSchoolService.addLwgyBaseSchool(lwgyBaseSchool);
        return Result.OK("添加成功！");
    }
*/

    /**
     * 编辑
     *
     * @param lwgyBaseSchool
     * @return
     */
    @AutoLog(value = "lwgy_base_school-编辑")
    @ApiOperation(value = "lwgy_base_school-编辑", notes = "lwgy_base_school-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody LwgyBaseSchool lwgyBaseSchool) {
        lwgyBaseSchoolService.updateLwgyBaseSchool(lwgyBaseSchool);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "lwgy_base_school-通过id删除")
    @ApiOperation(value = "lwgy_base_school-通过id删除", notes = "lwgy_base_school-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        lwgyBaseSchoolService.deleteLwgyBaseSchool(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "lwgy_base_school-批量删除")
    @ApiOperation(value = "lwgy_base_school-批量删除", notes = "lwgy_base_school-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        //this.lwgyBaseSchoolService.removeByIds(Arrays.asList(ids.split(",")));
        List<String> strings = Arrays.asList(ids.split(","));
        for (String string : strings) {
            lwgyBaseSchoolService.deleteLwgyBaseSchool(string);
        }
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "lwgy_base_school-通过id查询")
    @ApiOperation(value = "lwgy_base_school-通过id查询", notes = "lwgy_base_school-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        LwgyBaseSchool lwgyBaseSchool = lwgyBaseSchoolService.getById(id);
        if (lwgyBaseSchool == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(lwgyBaseSchool);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param lwgyBaseSchool
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LwgyBaseSchool lwgyBaseSchool) {
        return lwgyBaseSchoolService.customerExportXls(request, lwgyBaseSchool, ImportSchool.class, "学院班级");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile file = fileMap.get("file");
        try {
            ImportParams params = new ImportParams();
			/*params.setTitleRows(2);
				params.setStartRows(1);*/
            params.setNeedSave(true);
            List<ImportSchool> list = ExcelImportUtil.importExcel(file.getInputStream(), ImportSchool.class, params);
            int size = list.stream().collect(Collectors.toSet()).size();
            Set<LwgyBaseSchool> set = new HashSet<>(500);
            String id;
            List<ImportSchool> importSchools = list.stream().filter(lwgyBaseSchool ->
                    lwgyBaseSchool.getCampusName() != null && !"".equals(lwgyBaseSchool.getCampusName()))
                    .collect(Collectors.toList());
            Map<String, String> map = new HashMap<>(importSchools.size());
            for (ImportSchool importSchool : importSchools) {
                id = "0";
                String campusName = importSchool.getCampusName();
                map = getSchoolInfo(set, id, campusName, "campus", map);
                String facultyName = importSchool.getFacultyName();
                map = getSchoolInfo(set, map.get("id"), facultyName, "faculty", map);
                String gradeName = importSchool.getGradeName();
                map = getSchoolInfo(set, map.get("id"), gradeName, "grade", map);
                String majorName = importSchool.getMajorName();
                map = getSchoolInfo(set, map.get("id"), majorName, "major", map);
                String className = importSchool.getClassName();
                map = getSchoolInfo(set, map.get("id"), className, "class", map);
            }
//				set.forEach((key,value)->{
//					lwgyBaseSchools.add(value);
//				});
            //lwgyBaseSchools.stream().sorted(Comparator.comparing(LwgyBaseSchool::getId)).forEach(System.out::println);
            ;
            List<LwgyBaseSchool> lwgyBaseSchools = set.stream().filter(lwgyBaseSchool -> lwgyBaseSchool.isExistFlag() == false).collect(Collectors.toList());
            lwgyBaseSchoolService.saveBatch(lwgyBaseSchools);
            return Result.OK("文件导入成功！班级数：" + size, null);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入失败");
        }


    }

    private Map<String, String> getSchoolInfo(Set<LwgyBaseSchool> set, String id, String campusName, String type, Map<String, String> map) {
        String pid = id;
        LwgyBaseSchool lwgyBaseSchool;
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", campusName);
        queryWrapper.eq("pid", id);
        queryWrapper.eq("del_flag", 0);
        List<LwgyBaseSchool> lwgyBaseSchools = lwgyBaseSchoolMapper.selectList(queryWrapper);
        String sysOrgCode = lwgyBaseSchoolMapper.getMaxSysOrgCode(pid);//查询最大的sysOrgCode
        String sysOrgCode1 = map.get(pid);
        if (oConvertUtils.isNotEmpty(sysOrgCode) && oConvertUtils.isNotEmpty(sysOrgCode1)) {//数据库和集合中的sysorgcode都不是空
            if (sysOrgCode.compareTo(sysOrgCode1) > 0) {//数据库中的大于于集合中的
                map.put(pid, sysOrgCode);//将集合中的更换为数据库中的
            }
        } else if (oConvertUtils.isEmpty(sysOrgCode)) {//数据库中的code为空
            map.put(pid, sysOrgCode1);//使用集合中的
        } else if (oConvertUtils.isEmpty(sysOrgCode1)) {//集合中的code为空
            map.put(pid, sysOrgCode);//使用数据库中的
        } else {//都为空
            sysOrgCode = "";
        }
        if (oConvertUtils.listIsEmpty(lwgyBaseSchools)) {
            lwgyBaseSchool = new LwgyBaseSchool();
            if (id == "0") {
                lwgyBaseSchool.setPid("0");
            } else {
                lwgyBaseSchool.setPid(id);
            }
            id = String.valueOf(snowflake.snowflakeId());//获取分布式的id
            lwgyBaseSchool.setId(id);
            lwgyBaseSchool.setName(campusName);
            lwgyBaseSchool.setDelFlag("0");
            lwgyBaseSchool.setHasChild("1");
            lwgyBaseSchool.setType(type);
            lwgyBaseSchool.setUniversitySort(type);
            List<LwgyBaseSchool> collect = set.stream().filter(lwgyBaseSchool1 -> lwgyBaseSchool1.getId().equals(pid)).collect(Collectors.toList());
            String pSysOrgCode = "";
            if (oConvertUtils.listIsNotEmpty(collect)) {
                LwgyBaseSchool lwgyBaseSchool1 = collect.get(collect.size() - 1);
                pSysOrgCode = lwgyBaseSchool1.getSysOrgCode();
            }
            sysOrgCode = YouBianCodeUtil.getSubYouBianCode(pSysOrgCode, map.get(pid));
            lwgyBaseSchool.setSysOrgCode(sysOrgCode);
            lwgyBaseSchool.setExistFlag(false);
        } else {
            lwgyBaseSchool = lwgyBaseSchools.get(0);
            sysOrgCode = lwgyBaseSchool.getSysOrgCode();
            lwgyBaseSchool.setExistFlag(true);
            id = lwgyBaseSchool.getId();
        }
        map.put(pid, sysOrgCode);//把最后的code放入map
        List<LwgyBaseSchool> schoolList = set.stream().filter(baseSchool ->
                baseSchool.getPid().equals(pid)).filter(baseSchool ->
                baseSchool.getName().equals(campusName)).collect(Collectors.toList());
        if (schoolList.size() <= 0) {
            set.add(lwgyBaseSchool);
        } else {
            id = schoolList.get(0).getId();
        }
        map.put("id", id);
		 /*}else {
			 id = lwgyBaseSchool.getId();
		 }*/

        return map;
    }

    public List<String> mapToList(Map<String, String> map) {
        List<String> list = new ArrayList<>(20);
        map.forEach((key, value) -> {
            list.add(value);
        });
        return list;
    }
/*
    @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
    public Result<List<SchoolTreeModel>> queryTreeList() {
        Result<List<SchoolTreeModel>> result = new Result<>();

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String ids = sysBaseAPI.querySchoolCodeByUserId(sysUser.getId());

        List<SchoolTreeModel> list = lwgyBaseSchoolService.queryTreeList();
        result.setResult(list);
        result.setSuccess(true);

        return result;
    }*/

   /* @GetMapping("/getSchoolCodeById")
    public Result<?> getSchoolCodeById(String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String selectedSchools = commonAPI.getCacheUser(sysUser.getUsername()).getSelectedSchools();

        LwgyBaseSchool lwgyBaseSchool = lwgyBaseSchoolService.getById(id);
        String sysOrgCode = lwgyBaseSchool.getSysOrgCode();
        boolean b = lwgyBaseBedController.permissionTest(selectedSchools, sysOrgCode);
        return Result.OK(b);
    }*/


    @PutMapping("/setChooseTime")
    public Result<?> setChooseTime(@RequestBody LwgyBaseSchool lwgyBaseSchool) {
        String ids = lwgyBaseSchool.getIds();
        List<String> idList = Arrays.asList(ids.split(","));
        List<LwgyBaseSchool> classList = new ArrayList<>(10);
        QueryWrapper<LwgyBaseSchool> queryWrapper;
        for (String id : idList) {
            queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id", "university_sort");
            queryWrapper.eq("id", id);
            LwgyBaseSchool lwgyBaseSchool1 = lwgyBaseSchoolMapper.selectOne(queryWrapper);
            List<LwgyBaseSchool> lwgyBaseClass = lwgyBaseSchoolService.selectClassList(lwgyBaseSchool1);//查出该机构下所有班级
            classList.addAll(lwgyBaseClass);
        }
        for (LwgyBaseSchool baseSchool : classList) {
            baseSchool.setOpenTime(lwgyBaseSchool.getOpenTime());
            baseSchool.setEndTime(lwgyBaseSchool.getEndTime());
            baseSchool.setId(baseSchool.getClassId());
            baseSchool.setClassId(null);
//            baseSchool.setSysOrgCode();

        }
        lwgyBaseSchoolService.updateBatchById(classList);
        return Result.OK();
    }

    @GetMapping("/getTreeChild")
    public Result<?> getTreeChild(String pid) {
        List<LwgyBaseSchool> apartmentList = lwgyBaseSchoolService.getTreeChild(pid);//获取数据
        return Result.OK(apartmentList);
    }


    /**
     * 根据部门id查询用户信息
     *
     * @param id
     * @return
     */
 /*   @RequestMapping(value = "/queryUserBySchId", method = RequestMethod.GET)
    public Result<?> queryUserByDepId(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "realname", required = false) String realname) {

        //List<SysUser> userList = sysUserDepartService.queryUserByDepId(id);
        LwgyBaseSchool lwgyBaseSchool = lwgyBaseSchoolService.getById(id);
        Page<SysUser> page = new Page<>();
        IPage<SysUser> userList = lwgyBaseSchoolService.queryUserByDepCode(page,lwgyBaseSchool.getSysOrgCode(), realname);
        try {

            return Result.OK(userList);
        } catch (Exception e) {
            return Result.error("服务器内部错误");
        }
    }*/


    @ApiOperation(value = "getSchoolChildByPid", notes = "getSchoolChildByPid")
    @GetMapping("/getSchoolChildByPid")
    public Result<?> getSchoolChildByPid(String pid) {
        List<LwgyBaseSchool> treeChild = lwgyBaseSchoolService.getSchoolChildByPid(pid);
        return Result.OK(treeChild);
    }

    @ApiOperation(value = "getAllCampus", notes = "getAllCampus")
    @GetMapping("/getAllCampus")
    public Result<?> getAllCampus() {
        List<LwgyBaseSchool> schoolList = lwgyBaseSchoolService.getSclCampus();
        List<LwgyBaseApartment>buildCampus = lwgyBaseApartmentService.getBuildCampus();
        HashMap<String, Object> data = new HashMap<>();
        data.put("SclCampus",schoolList);
        data.put("buildCampus",buildCampus);
        return Result.OK(data);
    }
}
